const mergeInterval = (intervals: Array<Array<number>>) => {
  if (!intervals || intervals.length < 2) return intervals

  const res: Array<Array<number>> = []

  intervals
    .sort((a, b) => a[0] - b[0])
    .forEach(interval => {
      if (res.length === 0) {
        res.push(interval)
        return
      }

      /** 当前区域的左边界 */
      const curIntervalStart = interval[0]
      /** 当前区域的右边界 */
      const curIntervalEnd = interval[1]
      /** 结果中的最后一个区域 */
      const preInterval = res[res.length - 1]
      /** 结果中的最后一个区域的右边界 */
      let preIntervalEnd = preInterval[1]

      if (curIntervalStart > preIntervalEnd) {
        //无重合
        res.push(interval)
      } else {
        //存在重合区域
        if (curIntervalEnd > preIntervalEnd) {
          preIntervalEnd = curIntervalEnd
          res[res.length - 1][1] = preIntervalEnd //更新 res 中最后一个区间的右边界
        }
      }
    })

  return res
}

export const highlightKeywords = (content: string, keywords: Array<string>) => {
  let res = ''

  const newKeywords = keywords.map(item => {
    return item.toLocaleLowerCase()
  })

  const newContent = content.toLocaleLowerCase()

  let highlightIntervals: Array<Array<number>> = []

  newKeywords.forEach(keyword => {
    let index = 0

    while (newContent.indexOf(keyword, index) !== -1) {
      const startPosition = newContent.indexOf(keyword, index)
      const endPosition = startPosition + keyword.length
      highlightIntervals.push([startPosition, endPosition])
      index = endPosition
    }
  })

  highlightIntervals = mergeInterval(highlightIntervals)

  let index = 0

  highlightIntervals.forEach(interval => {
    const intervalStart = interval[0]
    const intervalEnd = interval[1]

    res += content.substring(index, intervalStart)
    res += `<span style="color: red;">${content.substring(
      intervalStart,
      intervalEnd
    )}</span>`

    index = intervalEnd
  })

  if (index < content.length) {
    res += content.substring(index)
  }

  return res
}
